package Controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hr-system/Global"
	"hr-system/Model"
	"hr-system/Response"
	"log"
	"net/http"
	"strings"
)

func Login(c *gin.Context) {
	DB := Global.GetDB()
	// 获取参数

	var user Model.User

	c.ShouldBind(&user)
	fmt.Println(user)
	id := user.Id
	password := user.Password
	// 判断账号是否存在
	var duser Model.User
	result := DB.Where("id=?", id).First(&duser)
	if result.RowsAffected == 0 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		return
	}
	// 判断密码是否正确
	if strings.Compare(duser.Password, password) != 0 {
		response.Response(c, http.StatusBadRequest, 400, nil, "密码错误")
		return
	}
	// 发放TOKEN
	token, err := Global.ReleaseToken(duser)
	if err != nil {
		response.Response(c, http.StatusInternalServerError, 500, nil, "token发放失败")
		log.Printf("token generate error: %v", err)
		return
	}

	// 返回结果
	response.Success(c, gin.H{"token": token, "data":id}, "登录成功")
}
